import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
  // 是否不需要设置 token
  // 同时检查header和headers，以兼容两种写法
  const noToken = (config.header || config.headers || {}).isToken === false
  config.header = config.header || {}
  
  // 调试日志
  console.log('请求URL:', config.url)
  console.log('请求配置:', JSON.stringify(config))
  console.log('noToken:', noToken)
  console.log('是否携带token:', !noToken && !!getToken())
  
  // 获取当前页面路径用于调试
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const currentPath = currentPage ? currentPage.route : '未知页面'
  console.log('当前页面路径:', currentPath)
  if (getToken() && !noToken) {
      config.header['Authorization'] = 'Bearer ' + getToken()
    }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
    // 设置默认Content-Type
    config.header['Content-Type'] = config.header['Content-Type'] || 'application/json';
    
    // 调试网络请求配置
    console.log('===== 网络请求开始 =====');
    console.log('请求URL:', config.baseUrl || baseUrl + config.url);
    console.log('请求方法:', config.method || 'get');
    console.log('请求头:', JSON.stringify(config.header));
    console.log('请求数据:', JSON.stringify(config.data));
    console.log('withCredentials设置为true，解决跨域问题');
    console.log('========================\n');
    
    uni.request({
        method: config.method || 'get',
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json',
        withCredentials: true // 增加withCredentials配置，解决跨域问题
      }).then(response => {
        let [error, res] = response
        if (error) {
          console.error('请求错误:', error)
          toast(`后端接口连接异常: ${error.errMsg || error.message}`)
          reject(`后端接口连接异常: ${error.errMsg || error.message}`)
          return
        }
        const code = res.data.code || 200
        const msg = errorCode[code] || res.data.msg || errorCode['default']
        if (code === 401) {
          // 获取当前页面路径
          const pages = getCurrentPages()
          const currentPage = pages[pages.length - 1]
          const currentPath = currentPage ? currentPage.route : '未知页面'
          
          console.log('401错误 - 当前页面路径:', currentPath)
          
          // 检查当前请求是否是发送验证码或登录请求
          const isAuthRequest = config.url.includes('/auth/sendCode') || config.url.includes('/auth/login') || config.url.includes('/auth/driverLogin')
          console.log('是否是认证相关请求:', isAuthRequest)
          
          // 检查当前页面是否是登录页面或司机登录页面，或者请求是否是认证相关请求
          if ((currentPath !== 'pages/login' && currentPath !== 'pages/driver-login/driver-login') && !isAuthRequest) {
            showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
              if (res.confirm) {
                store.dispatch('LogOut').then(res => {
                  uni.reLaunch({ url: '/pages/login' })
                })
              }
            })
          } else {
            console.log('在登录页面、司机登录页面或发送认证请求时遇到401错误，不弹出提示')
          }
          reject('无效的会话，或者会话已过期，请重新登录。')
        } else if (code === 500) {
          toast(msg)
          reject('500')
        } else if (code !== 200) {
          toast(msg)
          reject(code)
        }
        resolve(res.data)
      })
      .catch(error => {
        let { message } = error
        if (message === 'Network Error') {
          message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        toast(message)
        reject(error)
      })
  })
}

export default request
